package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询分类
     * @param curPage
     * @param pageSize
     * @return
     */
    @GetMapping("page")
    public R<Page<Category>> queryCategoryByPage(@RequestParam("page") Integer curPage, Integer pageSize) {
        Page<Category> page = new Page<>(curPage, pageSize);
        categoryService.lambdaQuery()
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime)
                .page(page);
        return R.success(page);
    }

    /**
     * 新增分类
     * @param category
     * @param request
     * @return
     */
    @PostMapping
    public R<String> addCategory(@RequestBody Category category, HttpServletRequest request) {
        categoryService.save(category);
        return R.success("添加分类成功");
    }

    /**
     * 修改分类
     * @param category
     * @param request
     * @return
     */
    @PutMapping
    public R<String> updateCategory(@RequestBody Category category, HttpServletRequest request) {
        categoryService.updateById(category);
        return R.success("分类修改成功");
    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleteCategory(Long id) {
        categoryService.deleteCategoryByCondition(id);
        return R.success("删除分类成功");
    }

    /**
     * 根据type查询分类
     * @param type
     * @return
     */
    @GetMapping("list")
    public R<List<Category>> getCategoryList(Integer type) {
        List<Category> categories = categoryService.lambdaQuery()
                                                .eq(type != null, Category::getType, type)
                                                .orderByAsc(Category::getSort)
                                                .list();
        return R.success(categories);
    }
}
